package com.googlecode.gwtbb.server.intermediate.picture;

import com.googlecode.gwtbb.client.shared.util.PictureUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Dec 4, 2008
 */
public class Watermarker {
	private static Log log = LogFactory.getLog(Watermarker.class);

	private String watermarkResourceName;
	private BufferedImage watermarkImage;
	// the amount of area the watermark should take up of the image, between 0 and 1
	private double watermarkAreaRatio = 0.01;
	private double watermarkAspectRatio;

	public double getWatermarkAreaRatio() {
		return watermarkAreaRatio;
	}

	public void setWatermarkAreaRatio(double watermarkAreaRatio) {
		this.watermarkAreaRatio = watermarkAreaRatio;
	}

	public String getWatermarkResourceName() {
		return watermarkResourceName;
	}

	public void setWatermarkResourceName(String watermarkResourceName) {
		this.watermarkResourceName = watermarkResourceName;
		try {
			watermarkImage = ImageIO.read(getWatermarkStream(watermarkResourceName));
			watermarkAspectRatio = PictureUtils.getAspectRatio(watermarkImage.getWidth(), watermarkImage.getHeight());
		} catch (IOException e) {
			watermarkImage = null;
			watermarkAspectRatio = 0;
			log.error("could not read watermark from file: " + watermarkResourceName, e);
		}
	}

	public void watermark(Graphics g, int picWidth, int picHeight) {
		// add a watermark if we have one
		if (watermarkImage != null && watermarkAreaRatio > 0) {
			double picAspectRatio = PictureUtils.getAspectRatio(picWidth, picHeight);
			int numWatermarkPixels = (int)Math.round(watermarkAreaRatio * (picWidth * picHeight));
			int wtrWidth, wtrHeight;
			if (picAspectRatio > watermarkAspectRatio) {
				wtrHeight = (int)Math.round(Math.sqrt(numWatermarkPixels / watermarkAspectRatio));
				if (wtrHeight > picHeight)
					wtrHeight = picHeight;
				wtrWidth = (int)(wtrHeight * watermarkAspectRatio);
			} else {
				wtrWidth = (int)Math.round(Math.sqrt(numWatermarkPixels * watermarkAspectRatio));
				if (wtrWidth > picWidth)
					wtrWidth = picWidth;
				wtrHeight = (int)(wtrWidth / watermarkAspectRatio);
			}
			Image wtrImage = watermarkImage.getScaledInstance(wtrWidth, wtrHeight, Image.SCALE_SMOOTH);

			// todo enhancement make watermark location configurable
			g.drawImage(wtrImage, picWidth - wtrWidth, picHeight - wtrHeight, null);
		}
	}

	protected InputStream getWatermarkStream(String watermarkResourceName) {
		return getClass().getClassLoader().getResourceAsStream(watermarkResourceName);
	}
}
